<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>公众号授权</title>
    <script src="https://assets.ckjr001.com/axios-v0.15.3.min.js"></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
  </head>

  <body>
    <script>
      /**
       * 跳转到这个页面携带的参数
       * companyId:公司id - required
       * openFrom:来自哪里，required  1-主播观看小程序
       * openId:
       * uniondId:
       * */
      let axiosInstance;
      // https://kptest.ckjr001.com/wechatPublicPlatformAuth.html?env=1&companyId=lj7l&from=1&uri=%252Frooms%252Fpages%252Fvertical%252Findex%253FliveId%253D24939%2526socialRoomId%253D34562%2526env%253D1%2526companyId%253Dlj7l&timestamp=1741763781781
      // https://kptest.ckjr001.com/wechatPublicPlatformAuth.html?env=1&companyId=lj7l&from=1&uri=%252Frooms%252Fpages%252Fvertical%252Findex%253FliveId%253D24939%2526socialRoomId%253D34562%2526env%253D1%2526companyId%253Dlj7l&timestamp=1741763781781
      // openId uniondId  c:公司id  backUrl:回调的地址   uri=%2Frooms%2Fpages%2Fvertical%2Findex%3FliveId%3D24939%26socialRoomId%3D34562%26env%3D1%26companyId%3Dlj7l
      function getQueryParams(url) {
        const params = {};
        if (url && url.indexOf('?') != -1) {
          const paramArr = url.slice(url.indexOf('?') + 1).split('&');
          paramArr.map(param => {
            const [key, val] = param.split('=');
            params[decodeURIComponent(key)] = decodeURIComponent(val);
          });
        }
        return params;
      }
      function serializeParams(obj = {}) {
        return Object.keys(obj)
          .map(key => {
            const value = obj[key];
            // 对键和值进行URL编码
            return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
          })
          .join('&');
      }
      function getEnvConfig() {
        let host = window.location.host;
        let env = 3; // 默认正式换将
        let apiUrl = 'https://kpapiop.ckjr001.com';
        let appIds = null;
        if (host.indexOf('kptest') != -1) {
          env = 1;
        } else if (host.indexOf('formal') != -1) {
          env = 2;
        }
        if (env == 1) {
          apiUrl = 'https://kpapi-cs.ckjr001.com';
          // apiUrl = 'https://kpapi-cs2.ckjr001.com';
        } else if (env == 2) {
          apiUrl = 'https://formalapi.ckjr001.com';
        }
        return {
          env: env,
          apiUrl: apiUrl
        };
      }

      function pageOnLoad(browserEnv) {
        let queryParams = getQueryParams(window.location.href);
        if (queryParams.t && queryParams.u) {
          // alert("授权成功:" + JSON.stringify(queryParams));
          console.log("授权成功", queryParams)
          // 授权通过
          wx.miniProgram.postMessage({
            data: {
              ...queryParams,
              token: queryParams.t
            }
          });
          wx.miniProgram.navigateBack()
          // if (queryParams.openFrom == 1) {
          //   // 直播观看小程序
          //   wx.miniProgram.redirectTo({
          //     url: '/rooms/pages/wechatPublicPlatformBridge/index'
          //   });
          // } else if (queryParams.openFrom == 2 || queryParams.openFrom == 3) {
          //   // 创匠推客小程序
          //   wx.miniProgram.navigateBack()
          // }
          // 其他的不同应用通过from来区分处理不同的逻辑
        } else {
          // 非授权没通过
          const { com_refereeId, prodId, prodType, openId, uniondId, refereeId } = queryParams;
          let urlQuery=`c=${queryParams.companyId}&openFrom=${queryParams.openFrom}`;
          if (queryParams.openFrom == 1 || browserEnv == 1) {
            urlQuery += `&chl=xcx`;
          }
          if(com_refereeId){
            urlQuery += `&r=${queryParams.com_refereeId}`;
          }
          if (prodId) {
            urlQuery +=`&prodId=${prodId}`;
          }
          if (prodType) {
            urlQuery +=`&prodType=${prodType}`;
          }
          if (openId) {
            urlQuery +=`&openId=${openId}`;
          }
          if (uniondId) {
            urlQuery +=`&uniondId=${uniondId}`;
          }
          if (refereeId) {
            urlQuery +=`&refereeId=${refereeId}`;
          }
          // 二次授权的时候
          if(queryParams.u) {
            urlQuery +=`&u=${queryParams.u}`;
          }
          urlQuery +=`&backUrl=${encodeURIComponent(window.location.href)}`;
          console.log("urlQuery", urlQuery)
          let envConfig = getEnvConfig();
          initAuth(`${envConfig.apiUrl}/api/mp/initAuth?${urlQuery}`).then(url => {
            if (url.indexOf('?') == -1) {
              url = `${url}?timestamp=${new Date().getTime()}`;
            } else {
              url = `${url}&timestamp=${new Date().getTime()}`;
            }
            window.location.replace(url);
          });
        }
      }
      function initAuth(url, data) {
        return new Promise((resolve, reject) => {
          axiosInstance.get(url,{ params: data }).then(res => {
            console.log('res', res);
            if (res.status == 200) {
              if (Object.prototype.toString.call(res.data) == '[object String]') {
                resolve(res.data);
              } else {
                alert(JSON.stringify(res.data));
                reject(res);
              }
            } else {
              alert(JSON.stringify(res.data));
              reject(res);
            }
          });
        });
      }

      window.onload = () => {
        let queryParams = getQueryParams(window.location.href);
        let axiosConfig = {
          headers: {
            'Content-Type': 'application/json;charset=UTF-8',
          },
          timeout: 20000
        }
        console.log("queryParams.storeId", queryParams.storeId)
        if(queryParams.storeId){
          axiosConfig.headers["X-STORE-ID"] = queryParams.storeId;
        }
        axiosInstance = axios.create(axiosConfig);
        wx.miniProgram.getEnv(function(res) {
          if (res.miniprogram) {
            pageOnLoad(1);
          } else {
            pageOnLoad();
          }
        });
      };
    </script>
  </body>
</html>
